import allure
from selenium.common import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

from page.base_page import BasePage


class LoanDetailsReport(BasePage):
    __order_management = By.XPATH, "//*[text()='订单管理']"
    __proxy_order = By.XPATH, "//*[text()='代理订单']"
    __proxy_order_list = By.XPATH, "//*[@href = '/order/proxyOrder/proxyOrderApply']"
    __loan_amount_summary = By.XPATH, "//*[@class='mb10 search-button']/div"
    __loan_details_report = By.XPATH, '//*[@href="/statistics/proxyReport/disburseDetails"]/div'

    def goto_proxy_order(self):
        from page.proxy_order_apply_page import ProxyOrderApply
        with allure.step('点击订单管理'):
            self.find_and_click(self.__order_management)
        with allure.step('点击代理订单'):
            self.find_and_click(self.__proxy_order)
        with allure.step('点击订单列表'):
            self.find_and_click(self.__proxy_order_list)
            self.wait(EC.visibility_of_element_located((By.XPATH, "//*[text()='借贷人姓名']")), time_out=10)
        return ProxyOrderApply(self.driver)

    def get_loan_amount_summary(self):
        with allure.step("获取放款金额汇总"):
            while True:
                try:
                    loan_amount_summary = self.find(self.__loan_amount_summary).text
                    loan_amount_summary = loan_amount_summary.split("：")[1]
                    break
                except (StaleElementReferenceException, IndexError):
                    pass
        return loan_amount_summary

    def get_first_loan_details(self):
        with allure.step("获取第一条放款记录"):
            loan_details = []
            try:
                self.wait(EC.presence_of_element_located((By.XPATH, "//*[@class = 'el-table__body']/tbody/tr[1]")))
                for i in range(4, 9):
                    loan_details.append(self.find(By.XPATH, f"//*[@class = 'el-table__body']/tbody/tr[1]/td[{i}]").text)
            except StaleElementReferenceException:
                pass
        return loan_details
